﻿// QLZ_For_Cplusplus_Demo.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include "i_qlz.h"

FILE* depofile = NULL;

char* fifo = new char[4096];

void data_callback(int block_len)
{
    if(depofile != NULL)
        fwrite(fifo, block_len, 1, depofile);
}

void press_file(const char *src_file, const char *dst_file)
{
    FILE* ifile = NULL, * ofile = NULL;
    errno_t err;
    err = fopen_s(&ifile, src_file, "rb");
    err = fopen_s(&ofile, dst_file, "wb");
    struct stat statbuf;
    stat(src_file, &statbuf);
    int len = statbuf.st_size;
    //fseek(ifile, 0, SEEK_END);
    //int len = ftell(ifile);
    //fseek(ifile, 0, SEEK_SET);
    char* file_data = (char*)malloc(len);
    char* press_data = (char*)malloc(len);
    fread(file_data, 1, len, ifile);

    i_qlz_compress(file_data, press_data, &len);
    fwrite(press_data, len, 1, ofile);
    fclose(ifile);
    fclose(ofile);
    free(file_data);
    free(press_data);
}

void depress_file(const char* src_file, const char* dst_file)
{
    FILE* ifile = NULL;
    errno_t err;
    err = fopen_s(&ifile, src_file, "rb");
    err = fopen_s(&depofile, dst_file, "wb");
    struct stat statbuf;
    stat(src_file, &statbuf);
    int len = statbuf.st_size;
    char* file_data = (char*)malloc(len);
    fread(file_data, 1, len, ifile);

    i_qlz_decompress(file_data, len, fifo,data_callback);

    /* //4K解压测试
    int sector_num = (len % 4096) ? (len / 4096  + 1) : (len / 4096);
    for (int i = 0; i < sector_num; i++)
    {
        i_qlz_decompress(file_data + i * 4096, 4096, fifo, data_callback);
    }
    */

    fclose(ifile);
    fclose(depofile);
    free(file_data);
}

int main()
{
    const char* src_press_file = "../bin/x64/debug/press_src.bin";
    const char* dst_press_file = "../bin/x64/debug/press_dst_ot.bin";
    const char* src_depress_file = "../bin/x64/debug/press_dst_ot.bin";
    const char* dst_depress_file = "../bin/x64/debug/depress_dst_ot.bin";

    press_file(src_press_file, dst_press_file);
    depress_file(src_depress_file, dst_depress_file);
    return 0;
}
